import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { routerRedux, Link } from 'dva/router';
import moment from 'moment';
import {
    Row, Col, Card, Form, Input,
    Select, Icon, Button, Dropdown, Menu,
    InputNumber, DatePicker, Modal, message,
    Divider, Tag, Table, Pagination, Spin, Upload
    , AutoComplete, TreeSelect
} from 'antd';
import StandardTable from '../../components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import DescriptionList from '../../components/DescriptionList';
import styles from './ChannelMaintenance.less';
import { solo } from '../../common/solo';
import { validatemobile } from '../../utils/utils';


const { Description } = DescriptionList;
const FormItem = Form.Item;
const { Option } = Select;
const { MonthPicker, RangePicker } = DatePicker;
const TreeNode = TreeSelect.TreeNode;
/*
  渠道管理的渠道维护界面
*/
let token = sessionStorage.getItem("token");
let tableListDataSource = [];
const channelState = ["未激活", "正常", "启动", "暂停"]

@connect(({ channel }) => ({
    channel,
}))
@Form.create()
export default class ChannelMaintenance extends PureComponent {
    state = {
        isFlag: false,
        modalVisible: false,
        previewVisible: false,
        previewImage: '',
        fileList: [],
        fileListName: '',
        formValues: {},
        dataTime: [],
        dataTimeFlag: false,
        branchName: '',
        value: undefined,
        uploadButtonChangeState: true,
        searchFilters: {
            merchantName: '',
            branchName: '',
            startDate: '',
            endDate: '',
        },
        branchTreeList: null,
        uploadingPicture: false,
    };

    componentDidMount() {
        const { dispatch } = this.props;

        dispatch({
            type: 'channel/getBranchTreeList',

            callback: () => {
                const { channel: { branchTreeList } } = this.props;
                branchTreeList &&
                    this.setState({
                        branchTreeList: branchTreeList,
                    })
            }
        });
        dispatch({
            type: 'channel/fetch',
            payload: {
                offset: 0,
                limit: 10,
            },
        });
    }

    wrapTreeDataRecord = (record) => {
        return (
            <TreeNode
                title={record.orgName}
                value={record.id}
                key={record.id}
                dataRef={record}
            >
                {
                    record.children && record.children.length > 0 && record.children.map((item) => {
                        return this.wrapTreeDataRecord(item)
                    })
                }
            </TreeNode>
        );
    }

    handleRemoveImage = (e) => {
        this.setState({
            uploadButtonChangeState: false,
            uploadingPicture: false,
            fileList: this.state.fileList.filter((item) => {
                return item != e.response.body.key;
            }),
        });
    }

    onUploadChange = (info) => {
        this.setState({
            uploadButtonChangeState: false,
        })
        // console.log("onUploadChange", info)
        if (info.file.status === 'done') {
            const newFileList = [...this.state.fileList];
            newFileList.push(info.file.response.body.key);
            this.setState({
                fileList: newFileList,
                fileListName: info.file.response.body.key
            });
            if (info.file.response.body.key) {
                // this.setState({
                //     fileList: newFileList,
                //     fileListName: info.file.response.body.key
                // });
                message.success("图片上传成功")
            } else {
                message.error("图片上传失败")
            }
            this.setState({
                uploadingPicture: false,
            });
        } else if (info.file.status === 'err') {
            message.error(`${info.file.name} 照片上传失败`);
            this.setState({
                uploadingPicture: true,
            });
        } else if (info.file.status === 'uploading') {
            this.setState({
                uploadingPicture: true,
            });
        }
    }

    handleStandardTableChange = (e) => {
        this.props.dispatch({
            type: 'channel/fetch',
            payload: {
                offset: (e.current - 1) * e.pageSize,
                limit: e.pageSize,
                merchantName: this.state.searchFilters.merchantName,
                branchId: this.state.value,
                createTimeBegin: this.state.searchFilters.startDate,
                createTimeEnd: this.state.searchFilters.endDate,
            }
        });
        // this.props.dispatch({
        //     type: 'channel/fetch',
        //     payload: { offset: (e.current - 1) * e.pageSize, limit: e.pageSize },
        // });
    }

    handleSetState = (record, newState) => {
        this.props.dispatch({
            type: 'channel/changeChannelState',
            payload: {
                id: record.id,
                state: newState
            },
            callback: () => {
                this.props.dispatch({
                    type: 'channel/fetch',
                    payload: {
                        offset: 0,
                        limit: 10,
                    },
                });
            },
        });
    }

    handleAdd = () => {
        this.setState({
            modalVisible: true,
        });

    }
    handleChange = ({ fileList }) => this.setState({ fileList })

    handleCancel = () => this.setState({ previewVisible: false, })

    handleModalCancel = () => {
        // this.props.form.resetFields();
        this.setState({
            modalVisible: false,
        });
    }
    handlePreview = (file) => {
        this.setState({
            previewImage: file.url || file.thumbUrl,
            previewVisible: true,
        });
    }
    edit = (record) => {
        this.setState({ modalVisible: true })
    }

    hanleCreateUserModalOk = () => {
        const { validateFieldsAndScroll } = this.props.form;

        validateFieldsAndScroll((error, values) => {
            if (!error) {
                console.log("validateFieldsAndScroll", values)
                let phoneNum = validatemobile(values.phone)
                if (phoneNum) {
                    if (values != null) {
                        this.setState({
                            modalVisible: false,
                            previewImage: '',
                            fileList: [],
                        });
                    }
                    this.props.form.resetFields();
                    this.props.dispatch({
                        type: 'channel/add',
                        payload: {
                            merchantName: values.merchantName,
                            leader: values.leader,
                            regAddress: values.regAddress,
                            phone: values.phone,
                            licenseNo: values.licenseNo,
                            license: this.state.fileListName,
                        },
                        callback: () => {
                            this.props.dispatch({
                                type: 'channel/fetch',
                                payload: {
                                    offset: 0,
                                    limit: 10,
                                },
                            });
                        },
                    });
                } else {
                    message.warning("请输入正确的联系方式")
                }
            }
        });
    };

    handleChangeTime = (dates, dateString) => {
        this.setState({
            searchFilters: {
                ...this.state.searchFilters,
                startDate: dates[0],
                endDate: dates[1],
            }
        })
    }

    handleSearchNameChange = (e) => {
        this.setState({
            searchFilters: {
                ...this.state.searchFilters,
                merchantName: e.target.value,
            }
        })
    }

    handleSearch = (e) => {
        this.props.dispatch({
            type: 'channel/fetch',
            payload: {
                offset: 0,
                limit: 10,
                merchantName: this.state.searchFilters.merchantName,
                branchId: this.state.value,
                createTimeBegin: this.state.searchFilters.startDate,
                createTimeEnd: this.state.searchFilters.endDate,
            }
        });
    }

    handleFormReset = () => {
        const { form, dispatch } = this.props;
        form.resetFields();
        this.setState({
            dataTime: [],
            value: '',
            dataTimeFlag: false,
            searchFilters: {
                ...this.state.searchFilters,
                merchantName: '',
                branchName: '',
                startDate: '',
                endDate: '',
            }
        });
        dispatch({
            type: 'channel/fetch',
            payload: {
                offset: 0,
                limit: 10,
            },
        });
    }

    hanleTreeSelectChange = (value, info) => {
        this.setState({
            value: value,
            searchFilters: {
                ...this.state.searchFilters,
                branchName: info,
            }
        })
    }

    columns = [{
        title: '机构',
        dataIndex: 'merchantName',
        key: 'merchantName',
        render: (text, item) => {
            return (
                <div>
                    <strong>{item.merchantName}</strong>
                    {(item.state == 1 || item.state == 2) && <Tag color="green">{channelState[item.state]}</Tag>}
                    {(item.state == 0 || item.state == 3) && <Tag color="red">{channelState[item.state]}</Tag>}
                    <br />
                    地址：{item.regAddress}
                    <br />
                    账号：{item && item.merUserName}
                    {item.merchantNo &&
                        <div>
                            编号：{item.merchantNo}
                        </div>
                    }
                </div>
            );
        }
    }, {
        title: '负责人',
        dataIndex: 'leader',
        key: 'leader',
        render: (text, item) => {
            return (
                <div>
                    {item.leader}
                    <br />
                    电话：{item.phone}
                </div>
            );
        }
    }, {
        title: '创建时间',
        dataIndex: 'createTime',
        key: 'createTime',
    }, {
        title: '操作',
        dataIndex: 'state',
        key: 'id',
        render: (text, record) => (
            //0:未激活；1：正常；2：已启动；3：已暂停
            <Fragment>
                <Link to={`/channel/channel-details?id=${record.id}&state=1`}>详情</Link>
                <Divider type="vertical" />
                {record.state == '0' ? <Link to={`/channel/channel-details?id=${record.id}&state=2`}>激活</Link> : null}
                {record.state == '1' || record.state == '3' ? <a onClick={() => this.handleSetState(record, 2)}>启动</a> : null}
                {record.state == '2' ? <a onClick={() => this.handleSetState(record, 3)}>暂停</a> : null}
            </Fragment>
        )
    },
    ];

    renderSimpleForm() {
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 5 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 16 },
            },
        };
        return (
            <Form layout="inline">
                <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={10} sm={24}>
                        <FormItem label="机构名称">
                            <Input placeholder="请输入机构名称" value={this.state.searchFilters.merchantName} onChange={this.handleSearchNameChange} />
                        </FormItem>
                    </Col>
                    <Col md={10} sm={24}>
                        <FormItem  {...formItemLayout} label="所属支行">
                            <TreeSelect
                                style={{ width: '100%' }}
                                value={this.state.value}
                                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                                placeholder="请选择"
                                allowClear
                                treeDefaultExpandAll
                                onChange={this.hanleTreeSelectChange}
                            >
                                {this.state.branchTreeList &&
                                    this.state.branchTreeList.map((item) => {
                                        return this.wrapTreeDataRecord(item);
                                    })}
                            </TreeSelect>
                        </FormItem>
                    </Col>
                </Row>
                <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={10} sm={24}>
                        <FormItem label="创建时间">
                            <div>
                                <RangePicker
                                    style={{ width: '100%' }}
                                    allowClear={true}
                                    showToday={true}
                                    onChange={this.handleChangeTime}
                                    value={[
                                        this.state.dataTimeFlag ? null : this.state.searchFilters.startDate,
                                        this.state.dataTimeFlag ? null : this.state.searchFilters.endDate
                                    ]}
                                    showTime={{ hideDisabledOptions: true }}
                                    format="YYYY-MM-DD HH:mm:ss"
                                />
                            </div>
                        </FormItem>
                    </Col>
                    <span className={styles.submitButtons} style={{ textAlign: 'right' }}>
                        <Button type="primary" onClick={this.handleSearch}  >搜索</Button>
                        <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>重置</Button>
                    </span>
                </Row>
            </Form>
        );
    }

    render() {
        const { channel: { channelList, page, loading, branchTreeList }, confirmLoading, modalVisible1, } = this.props;
        const { getFieldDecorator, form, dispatch } = this.props;
        const { previewVisible, previewImage, fileList, modalVisible } = this.state;

        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 6 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 16 },
            },
        };

        const uploadButton = (
            <div>
                <Icon type="plus" />
                <div className="ant-upload-text">上传</div>
            </div>
        );

        return (
            <PageHeaderLayout title="渠道维护">
                <Card bordered={false}>
                    <div className={styles.tableList}>
                        <div className={styles.tableListForm}>
                            {this.renderSimpleForm()}
                        </div>
                        <div className={styles.tableListOperator}>
                            <Button icon="plus" type="primary" onClick={() => this.handleAdd()}>
                                新增
                            </Button>
                        </div>
                        <Table
                            dataSource={channelList}
                            pagination={page}
                            columns={this.columns}
                            loading={loading}
                            bordered
                            rowKey="id"
                            onChange={this.handleStandardTableChange}
                        />
                    </div>
                </Card>
                <Modal
                    title={'新增渠道'}
                    visible={this.state.modalVisible}
                    onOk={this.hanleCreateUserModalOk}
                    confirmLoading={confirmLoading}
                    onCancel={this.handleModalCancel}
                >
                    <Form>
                        <FormItem {...formItemLayout} label="公司名称" >
                            {
                                form.getFieldDecorator('merchantName', {
                                    rules: [{
                                        required: true, message: '请输入公司名称',
                                    }],
                                })(
                                    <Input placeholder="请输入公司名称" />
                                )}
                        </FormItem>
                        <FormItem {...formItemLayout} label="负责人" >
                            {form.getFieldDecorator('leader', {
                                rules: [{
                                    required: true, message: '请选择负责人',
                                }],
                            })(
                                <Input placeholder="请输入负责人" />
                            )}
                        </FormItem>
                        <FormItem {...formItemLayout} label="公司注册地址" >
                            {form.getFieldDecorator('regAddress', {
                                rules: [{
                                    required: true, message: '请输入公司注册地址',
                                }],
                            })(
                                <Input placeholder="请输入公司注册地址" />
                            )}
                        </FormItem>
                        <FormItem
                            {...formItemLayout} label="负责人联系方式" >
                            {form.getFieldDecorator('phone', {
                                rules: [{
                                    required: true, message: '请输入联系方式',
                                }],
                            })(
                                <InputNumber placeholder="请输入联系方式" style={{ marginLeft: 10, width: '100%' }} />
                            )}
                        </FormItem>
                        <FormItem {...formItemLayout} label="营业执照号" >
                            {form.getFieldDecorator('licenseNo', {
                                rules: [{
                                    required: true, message: '请输入营业执照号',
                                }],
                            })(
                                <Input placeholder="请输入营业执照号" style={{ width: '100%' }} />
                            )}
                        </FormItem>
                        <FormItem {...formItemLayout} label="营业执照上传" >
                            {form.getFieldDecorator('license', {
                                rules: [{
                                    required: true, message: '请上传营业执照',
                                }],
                            })(
                                <div  >
                                    {this.state.modalVisible && <Upload
                                        listType="picture-card"
                                        onPreview={this.handlePreview}
                                        name="img"
                                        action={solo.uploadImg}
                                        onChange={this.onUploadChange}
                                        onRemove={this.handleRemoveImage}
                                    >
                                        {!this.state.uploadingPicture && this.state.fileList.length < 1 ?
                                            <div>
                                                <Icon type="plus" />
                                                <div className="ant-upload-text">上传</div>
                                            </div>
                                            :
                                            null
                                        }
                                    </Upload>
                                    }
                                    <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
                                        <img alt="example" style={{ width: '100%' }} src={previewImage} />
                                    </Modal>
                                </div>
                            )}

                        </FormItem>
                    </Form>
                </Modal>

            </PageHeaderLayout>
        );
    }
}
